<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2020 http://yfcmf.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: rainfer <rainfer520@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model\setting;

use JwtUtil;
use app\admin\model\setting\AuthGroup as AuthGroupModel;

/**
 * 管理员相关操作
 */
class Admin extends \think\Model
{
    protected $autoWriteTimestamp = true;
    protected $createTime = 'regTime';
    protected $updateTime = 'updateTime';

    /**
     * 通过ID获取用户信息
     *
     * @param $uid
     *
     * @return array
     *
     * @throws
     */
    public static function getAdminById($uid)
    {
        $where [] = ['a.id', '=', $uid];
        $user = self::alias('a')->field('a.*,b.title')->join('auth_group b', 'a.groupId = b.id', 'left')->where($where)->find();
        return $user;
    }

    /**
     * 通过用户名获取用户信息
     *
     * @param $userName
     *
     * @return array
     *
     * @throws
     */
    public static function getAdminByName($userName)
    {
        $where = ['userName', '=', $userName];
        $user = self::alias('a')->field('a.*,b.title')->join('auth_group b', 'a.groupId = b.id', 'left')->where($where)->find();
        return $user;
    }

    /**
     * 获取管理员列表
     *
     * @param $userName
     * @param $phone
     * @param $realName
     * @param $startTime
     * @param $endTime
     * @param $isEnabled
     * @param $myOrder
     * @param $page
     * @param $pSize
     *
     * @return array
     *
     * @throws
     */
    public static function getLists($userName, $phone, $realName, $startTime, $endTime, $isEnabled, $myOrder, $page, $pSize)
    {
        $where = [];
        if ($userName) {
            $where[] = ['userName', 'like', '%' . $userName . '%'];
        }
        if ($phone) {
            $where[] = ['phone', 'like', '%' . $phone . '%'];
        }
        if ($realName) {
            $where[] = ['realName', 'like', '%' . $realName . '%'];
        }
        if ($startTime) {
            $where[] = ['loginTime', '>=', $startTime];
        }
        if ($endTime) {
            $where[] = ['loginTime', '<=', $endTime];
        }
        if ($isEnabled != -1) {
            $where[] = ['isEnabled', '=', $isEnabled];
        }
        return self::alias('a')->field('a.*,b.title')->join('auth_group b', 'a.groupId = b.id', 'left')->where($where)->order($myOrder)->page($page, $pSize)->select();
    }

    /**
     * 查询管理员得数量
     *
     * @param $userName
     * @param $phone
     * @param $realName
     * @param $startTime
     * @param $endTime
     * @param $isEnabled
     *
     * @return int
     *
     * @throws
     */
    public static function getTotal($userName, $phone, $realName, $startTime, $endTime, $isEnabled)
    {
        $where = [];
        if ($userName) {
            $where[] = ['userName', 'like', '%' . $userName . '%'];
        }
        if ($phone) {
            $where[] = ['phone', 'like', '%' . $phone . '%'];
        }
        if ($realName) {
            $where[] = ['realName', 'like', '%' . $realName . '%'];
        }
        if ($startTime) {
            $where[] = ['loginTime', '>=', $startTime];
        }
        if ($endTime) {
            $where[] = ['loginTime', '<=', $endTime];
        }
        if ($isEnabled != -1) {
            $where[] = ['isEnabled', '=', $isEnabled];
        }
        return self::where($where)->count();
    }

    /**
     * 检测用户名是否存在
     *
     * @param  $name
     *
     * @return int
     *
     * @throws
     */
    public static function checkAdmin($name)
    {
        $id = self::where('userName', $name)->value('id');
        if (empty($id)) {
            return 0;
        } else {
            return $id;
        }
    }

    /**
     * 设置密码
     *
     * @param $uid
     * @param $newPwd
     * @param $oldPwd
     *
     * @return mixed
     *
     * @throws
     */
    public static function setPwd($uid, $newPwd, $oldPwd)
    {
        $user = self::find($uid);
        if ($user['password'] !== encrypt_pass($oldPwd, $user['passwordSalt'])) {
            exception('原密码不正确');
        }
        $passSalt = random();
        $newPwd = encrypt_pass($newPwd, $passSalt);
        return self::where('id', $uid)->update(['password' => $newPwd, 'passwordSalt' => $passSalt]);
    }


    /**
     * 登录此时客户端的用户认证方式是JWT
     *
     * @param string $userName 登录主名称：用户名
     * @param string $password 未加密的密码
     *
     * @return array 对象数组，包含字段：userToken，已编码的用户访问令牌；user，用户信息。
     *
     * @throws
     */
    public static function login($userName, $password)
    {
        $$userName = trim($userName);
        $password = trim($password);
        // 查找身份，验证身份
        $user = self::where('userName', $userName)->find();
        if (empty($user)) {
            exception('用户不存在');
        }
        //密码验证
        if ($user['password'] !== encrypt_pass($password, $user['passwordSalt'])) {
            exception('密码不正确');
        }
        // 检测用户状态
        if ($user ['isEnabled'] != 1) {
            exception('用户被禁用');
        }
        // 数据处理和令牌获取
        $time = time();
        // 记录登录日志
        $group = AuthGroupModel::find($user['groupId']);
        model('system.LoginLog')->insert([
            'uid' => $user['id'],
            'userName' => $user['userName'],
            'roles' => $group['title'],
            'loginTime' => $time,
            'loginIp' => request()->ip()
        ]);
        $user['loginTime'] = $time;
        $user->save();
        // 令牌生成
        $payload['uid'] = $user['id'];
        $payload['loginTime'] = $time;
        $userToken = think_encrypt(JwtUtil::encode($payload));
        // 返回
        return array('userToken' => $userToken);
    }
}
